import React, { useEffect, useState } from 'react';
import { Button, Card, Image, Tag, Skeleton, message } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import { VarietyShowInfoDetail } from '@/services/VarietyShowInfo';
import { getVarietyShowInfoDetail } from '@/services/VarietyShowInfo';
import styles from './detail.less';

const VarietyDetail: React.FC = () => {
  const { idBase64 } = useParams<{ idBase64: string }>();
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<VarietyShowInfoDetail | null>(null);
  const [isHorizontal, setIsHorizontal] = useState(false);

  // 获取详情数据
  useEffect(() => {
    const fetchData = async () => {
      if (!idBase64) return;
      try {
        setLoading(true);
        // TODO: 替换为实际的获取详情接口
        const response = await getVarietyShowInfoDetail(parseInt(atob(idBase64)));
        setData(response);
      } catch (error) {
        message.error('获取综艺详情失败');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [idBase64]);

  // 处理返回列表
  const handleBack = () => {
    history.back();
  };

  // 处理字符串分割
  const splitString = (str?: string) => {
    if (!str) return [];
    return str
      .replace(/，/g, ',')
      .replace(/、/g, ',')
      .replace(/;/g, ',')
      .replace(/；/g, ',')
      .split(',')
      .map(item => item.trim())
      .filter(Boolean);
  };

  // 处理图片加载完成
  const handleImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
    const img = e.target as HTMLImageElement;
    setIsHorizontal(img.naturalWidth > img.naturalHeight);
  };

  // 基本信息展示
  const BasicInfo = () => {
    if (!data) return null;

    return (
      <div className={styles.infoGrid}>
        <div className={styles.mainInfo}>
          <h1 className={styles.title}>{data.title}</h1>
          <div className={styles.periodName}>{data.periodName}</div>
        </div>

        <div className={styles.infoList}>
          <div className={styles.infoItem}>
            <span className={styles.label}>期数</span>
            <span className={styles.value}>第 {data.period || 0} / {data.sumPeriod || 0} 期</span>
          </div>

          <div className={styles.infoItem}>
            <span className={styles.label}>播出时间</span>
            <span className={styles.value}>{data.releaseDate || '未知'}</span>
          </div>

          {data.language && (
            <div className={styles.infoItem}>
              <span className={styles.label}>语言</span>
              <span className={styles.value}>{data.language}</span>
            </div>
          )}

          {data.tags && (
            <div className={styles.infoItem}>
              <span className={styles.label}>标签</span>
              <span className={styles.value}>
                <div className={styles.tagList}>
                  {splitString(data.tags).map((tag, index) => (
                    <Tag key={index} color="blue">{tag}</Tag>
                  ))}
                </div>
              </span>
            </div>
          )}
        </div>
      </div>
    );
  };

  // 简介部分
  const Description = () => {
    if (!data?.description) return null;

    return (
      <div className={styles.description}>
        <div className={styles.label}>简介</div>
        <div className={styles.value}>{data.description}</div>
      </div>
    );
  };

  // 播放源列表
  const PlaySourceList = () => {
    if (!data?.playSourceInfo?.length) return null;

    return (
      <div className={styles.playSourceSection}>
        <h3 className={styles.sectionTitle}>播放源</h3>
        <div className={styles.sourceList}>
          {data.playSourceInfo.map((source, index) => (
            <a
              key={index}
              href={source.sourceUrl}
              target="_blank"
              rel="noopener noreferrer"
              className={styles.sourceItem}
            >
              {source.sourceName}
            </a>
          ))}
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <div className={styles.container}>
        <Card bodyStyle={{ padding: '16px' }}>
          <Skeleton active paragraph={{ rows: 10 }} />
        </Card>
      </div>
    );
  }

  if (!data) {
    return (
      <div className={styles.container}>
        <Card bodyStyle={{ padding: '16px' }}>
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <h3>未找到综艺信息</h3>
            <Button
              type="link"
              icon={<ArrowLeftOutlined />}
              onClick={handleBack}
            >
              返回
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <Card>
        <div className={styles.pageHeader}>
          <Button
            type="link"
            icon={<ArrowLeftOutlined />}
            onClick={handleBack}
            style={{ marginLeft: '-20px' }}
          >
            返回
          </Button>
          
        </div>

        <div className={`${styles.content} ${isHorizontal ? styles.horizontal : ''}`}>
        <h2>{data?.title}</h2>
          <div className={styles.mainContent}>
            <div className={styles.posterSection}>
              {data?.poster && (
                <div className={styles.posterWrapper}>
                  <Image
                    src={`/api/file/play/${data.poster}`}
                    alt={data.title}
                    className={styles.poster}
                    onLoad={handleImageLoad}
                  />
                </div>
              )}
            </div>
            <div className={styles.basicInfo}>
              <BasicInfo />
            </div>
          </div>
          <Description />
          <PlaySourceList />
        </div>
      </Card>
    </div>
  );
};

export default VarietyDetail; 